/**
 * @description 文件-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const ox = require('@daelui/oxjs')
const Service = require('./service.js')
const { filer } = require('@daelui/oxkit')
const path = require('path')
const fs = require('fs')
const multer = require('multer')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 表配置
    let config = this.route.scope.CONFIG
    // 服务
    this.$service = new Service(args)
    // // 创建上传目录
    // filer.buildPath(config.constant.uploadPath)
    // filer.buildPath(config.constant.uploadPath + '/tmp')
    // const app = this.route.app || (this.route.scope || {}).app
    // const router = (this.route.scope || {}).router || {}
    // // 1. 设置文件存放位置
    // let uploader = multer({
    //   storage: multer.diskStorage({
    //     destination (req, file, cb) {
    //       cb(null, config.constant.uploadPath + '/tmp')
    //     },
    //     filename (req, file, cb) {
    //       const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    //       cb(null, file.fieldname + '-' + uniqueSuffix)
    //     }
    //   }),
    //   fileFilter: (req, file, callback) => {
    //     // 解决中文名乱码的问题
    //     file.originalname = Buffer.from(file.originalname, 'latin1').toString(
    //       'utf8'
    //     )
    //     // 无权限
    //     if (!router.hasPermisson || !router.hasPermisson(req, {permission: {rules: ['admin']}}, app)) {
    //       removeTmp(req)
    //       callback(null, false)
    //     } else {
    //       callback(null, true)
    //     }
    //   }
    // })

    // app.post('/tigerlair/dfile/upload', uploader.single('file'), (req, res) => {   // file 与前端input 的name属性一致
    //   // 无权限
    //   if (!router.hasPermisson || !router.hasPermisson(req, {permission: {rules: ['admin']}}, app)) {
    //     removeTmp(req)
    //     let body = this.result({
    //       success: false,
    //       status: 401,
    //       msg: 'No Permission'
    //     })
    //     res.status(body.status || 200).send(body).end()
    //     return false
    //   }
    //   try {
    //     // 2. 上传的文件信息保存在req.file属性中
    //     // console.log(req.file)
    //     let oldName = req.file.path // 上传后默认的文件名 : 15daede910f2695c1352dccbb5c3e897
    //     let now = Date.now()
    //     let date = format(now, 23, '000').replace(/[^\w]+/g, '')
    //     let rand = String(Math.round(Math.random() * 1E9)).slice(0, 6)
    //     let fileName = req.file.originalname // (req.file.originalname).replace(/.*\./, date + '-' + rand + '.')
    //     // 按日存储
    //     let day = format(now, 10).replace(/[^\w]+/g, '')
    //     let dayPath = config.constant.uploadPath + '/' + day
    //     filer.buildPath(dayPath)
    //     let newName = dayPath + '/' + fileName // 指定文件路径和文件名
    //     // 3. 将上传后的文件重命名
    //     fs.renameSync(oldName, newName)
    //     // 4. 文件上传成功
    //     this.$service.add({
    //       params: {
    //         name: fileName,
    //         originName: req.file.originalname,
    //         path: path.join(newName, ''),
    //         ext: filer.getFileExt(req.file.originalname),
    //         data: '',
    //         size: req.file.size,
    //         description: '',
    //         order: 1,
    //         status: 1
    //       }
    //     }).then((resp) => {
    //       let id = resp.data
    //       let result = this.result({
    //         success: 1,
    //         data: { id: id }
    //       })
    //       res.send(result).end()
    //     }).catch(() => {
    //       removeTmp(req)
    //       let result = this.result({ success: 0 })
    //       res.send(result).end()
    //     })
    //   } catch (e) {
    //     removeTmp(req)
    //     let result = this.result({ success: 0 })
    //     res.send(result).end()
    //   }
    // })
  }

  /**
   * @function 上传
  */
  upload (action) {
    // 表配置
    let config = this.route.scope.CONFIG
  // 解析数据
    const req = action.req
    const res = action.res
    try {
      // 1. 上传的文件信息保存在req.file属性中
      let oldName = req.file.path // 上传后默认的文件名 : 15daede910f2695c1352dccbb5c3e897
      let now = Date.now()
      let date = format(now, 23, '000').replace(/[^\w]+/g, '')
      let rand = String(Math.round(Math.random() * 1E9)).slice(0, 6)
      let fileName = req.file.originalname // (req.file.originalname).replace(/.*\./, date + '-' + rand + '.')
      // 按日存储
      let day = format(now, 10).replace(/[^\w]+/g, '')
      let dayPath = config.constant.uploadPath + '/' + day
      filer.buildPath(dayPath)
      let newName = dayPath + '/' + fileName // 指定文件路径和文件名
      // 2. 将上传后的文件重命名
      fs.renameSync(oldName, newName)
      // 3. 文件上传成功
      return this.$service.add({
        params: {
          name: fileName,
          originName: req.file.originalname,
          path: path.join(newName, ''),
          ext: filer.getFileExt(req.file.originalname),
          data: '',
          size: req.file.size,
          description: '',
          order: 1,
          status: 1
        }
      }).then((resp) => {
        let id = resp.data
        let result = this.result({
          success: 1,
          data: { id: id }
        })
        return result
      }).catch(() => {
        removeTmp(req)
        let result = this.result({ success: 0 })
        return result
      })
    } catch (e) {
      removeTmp(req)
      let result = this.result({ success: 0, message: 'File Error' })
      return result
    }
  }

  /**
   * @function 上传前置处理
  */
  uploadMiddleware (req, res, next) {
    // 表配置
    let config = this.route.scope.CONFIG
    // 创建上传目录
    filer.buildPath(config.constant.uploadPath)
    filer.buildPath(config.constant.uploadPath + '/tmp')
    const app = this.route.app || (this.route.scope || {}).app
    const router = (this.route.scope || {}).router || {}
    // 1. 设置文件存放位置
    let uploader = multer({
      storage: multer.diskStorage({
        destination (req, file, cb) {
          cb(null, config.constant.uploadPath + '/tmp')
        },
        filename (req, file, cb) {
          const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
          cb(null, file.fieldname + '-' + uniqueSuffix)
        }
      }),
      fileFilter: (req, file, callback) => {
        // 解决中文名乱码的问题
        file.originalname = Buffer.from(file.originalname, 'latin1').toString(
          'utf8'
        )
        // 无权限
        if (!router.hasPermisson || !router.hasPermisson(req, {permission: {rules: ['admin']}}, app)) {
          removeTmp(req)
          callback(null, false)
        } else {
          callback(null, true)
        }
      }
    })

    return uploader.single('file')
  }

  /**
   * @function 部署
  */
  deploy (action) {
    // 解析数据
    return this.solveAction(action).then(async action => {
      let params = action.params || {}
      let files = params.files
      let pid = params.pid
      try {
        // 查询所有的文件数据
        let fileList = await this.$service.queryAll({
          params: {
            id: files
          },
          excute: {
            operators: [
              {field: 'id', operator: 'IN'}
            ],
            sort: [
              {field: 'createTime', by: 'desc'},
              {field: 'order', by: 'desc'}
            ]
          }
        })
        fileList = fileList.data
        // 查询所有的存储池数据
        let poolList = await this.$router.getControllInstance({name: 'pool'}).queryAll({}, {
          action: {},
          query: {},
          params: {
            id: pid
          },
          excute: {
            operators: [
              {field: 'id', operator: 'EQUAL'}
            ],
            sort: [
              {field: 'createTime', by: 'asc'},
              {field: 'order', by: 'desc'}
            ]
          }
        })
        poolList = poolList.data
        fileList = Array.isArray(fileList) ? fileList : []
        poolList = Array.isArray(poolList) ? poolList : []
        let config = this.route.scope.CONFIG
        poolList.forEach(pool => {
          fileList.forEach(item => {
            let poolPath = config.constant.poolPath
            let path = poolPath + ('/res/' + pool.path).replace('//', '/')
            filer.buildPath(path)
            filer.cpdir(item.path, path)
          })
        })
        return {data: {}, success: 1}
      } catch (e) {
        return {data: {}, success: 1}
      }
    })
  }

  /**
   * @function 增删改事件触发
  */
  // emit (name, action, res) {
  //   super.emit(name, action, res)
  //   res = res || {}
  // }
}

/**
 * @function 格式化时间
*/
const format = function simpleFormat(time, len, after) {
	var date = new Date(time)
	if (String(date) === 'Invalid Date') {
		return ''
	}
	var year= date.getFullYear()
	var month = date.getMonth() + 1
	var day = date.getDate()
	var hour = date.getHours()
	var minute = date.getMinutes()
	var second = date.getSeconds()
	var msecond = date.getMilliseconds()
	len = len || 19
	return [year, '-', month , '-', day, ' ', hour , ':', minute, ':', second, '.', msecond, (after || '') ].map(item => {
		return /^\d{1}$/.test(item) ? ('0' + item).slice(-2) : item
	}).join('').slice(0, len)
}

// 清除缓存
function removeTmp (req) {
  if (fs.existsSync(req?.file?.path)) {
    unlinkAsync(req.file.path)
  }
}

module.exports = Controller